#!C:/strawberry/perl/bin/perl.exe

use strict;
use warnings;

use CGI;
use RPC::XML;
use RPC::XML::Client;
use Data::Dumper;
use XML::Simple;
use XML::eXistDB::RPC;
use XML::Compile::RPC::Client;



# read the CGI params
my $cgi = CGI->new;
my $eXist = XML::eXistDB::RPC->new( destination=>"http://localhost:8080/exist/xmlrpc", repository=>"/db", user=>"admin", password=>"eaf2julian" ) ;
my $email = $cgi->param("email");
#my $email='email@email.com';
my $xquery = 'doc("/placeanddate/grupos.xml")/grupos/grupo[email/text() eq "'.$email.'"]' ;
my ($rc1, $set) = $eXist->executeQuery($xquery) ;
my ($rc2, $count) = $eXist->numberOfResults($set) ;
my ($rc3, @data) = $eXist->retrieveResults($set) ;
$eXist->releaseResultSet($set) ;

print $cgi->header( -type => 'text/plain' );
print Dumper(@data);


#print Dumper "------------------";
#print Dumper @data;
#print Dumper $count;
#print Dumper "------------------";
#print Dumper $data[0]{'grupo'};

my $lendata=$count;
#print Dumper ".....................................";
#print Dumper $data[0]{'grupo'}[1]{'email'};
#print Dumper $lendata;
my $json=  "{".qq{"grupos":[};
print $cgi->header(-type => "application/json", -charset => "utf-8");

while ($lendata>0) {
	my $nombre=$data[0]{'grupo'}[$lendata-1]{'nombre'};
	my @emails=$data[0]{'grupo'}[$lendata-1]{'email'};
	my $nemails=$#{$emails [0]}+1;
	$json = $json."{".qq{"nombre" : "$data[0]{'grupo'}[$lendata-1]{'nombre'}"};
	$json=$json.",";
	$json=$json.qq{"email":}."[";
	while ($nemails>0) {	
	# create a JSON string according to the database result
	$json = $json.qq{"$data[0]{'grupo'}[$lendata-1]{'email'}[$nemails-1]"};
	# return JSON string
	if ($nemails-1>0){
		$json=$json.",";
	}
	$nemails--;
	
	}
	$json=$json."]}";
	if ($lendata-1>0){
		$json=$json.",";
	}
	$lendata--;
}
$json=$json."]}";
print $json;
